package com.loves.admin.service.impl;

import com.loves.admin.model.Account;
import com.loves.admin.model.Role;
import com.loves.admin.service.AccountService;
import com.loves.admin.service.RoleService;
import com.loves.admin.service.UserRoleService;
import com.loves.admin.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Optional;

@Component
public class AccountUserDetailsServiceImpl implements UserDetailsService {

    private Logger logger = LoggerFactory.getLogger(AccountUserDetailsServiceImpl.class);

    @Resource
    private AccountService accountService;

    @Resource
    private RoleService roleService;

    @Resource
    private UserService userService;

    @Resource
    private UserRoleService userRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("登录用户名："+username);
        Account account = Optional.ofNullable(accountService.findByMailName(username))
                .orElseThrow(() -> new UsernameNotFoundException("用户名不存在"));
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        com.loves.admin.model.User user = userService.findByAccountId(account.getId());
        userRoleService.findByUserId(user.getId()).forEach(userRole -> {
            Role role = roleService.findById(userRole.getRoleId());
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        });
        return new User(account.getMailName(),account.getPassword(),authorities);
}
}
